package test

import com.gitee.ixtf.rsocket.RSocketMetadata
import io.netty.buffer.ByteBufAllocator
import io.netty.buffer.CompositeByteBuf
import io.netty.buffer.Unpooled
import io.rsocket.Payload
import io.rsocket.kotlin.*
import io.rsocket.kotlin.metadata.*
import io.rsocket.kotlin.payload.*
import io.rsocket.metadata.*
import io.rsocket.util.DefaultPayload
import io.vertx.kotlin.core.json.jsonObjectOf
import kotlinx.io.*

suspend fun main() {
  val payload = encodePayload()

  val metadata = RSocketMetadata(payload)
  println(metadata.route)
  println(metadata.messageMimetype)
}

private fun encodePayload(): Payload {
  val data = jsonObjectOf("command" to "command").toBuffer()
  val buf = CompositeByteBuf(ByteBufAllocator.DEFAULT, false, 8)
  CompositeMetadataCodec.encodeAndAddMetadata(
      buf,
      ByteBufAllocator.DEFAULT,
      WellKnownMimeType.MESSAGE_RSOCKET_ROUTING,
      TaggingMetadataCodec.createTaggingContent(ByteBufAllocator.DEFAULT, listOf("service")))
  CompositeMetadataCodec.encodeAndAddMetadata(
      buf,
      ByteBufAllocator.DEFAULT,
      WellKnownMimeType.MESSAGE_RSOCKET_MIMETYPE,
      Unpooled.wrappedBuffer(
          byteArrayOf(WellKnownMimeType.APPLICATION_CLOUDEVENTS_JSON.identifier)))
  return DefaultPayload.create(Unpooled.wrappedBuffer(data.bytes), buf)
}

@OptIn(ExperimentalMetadataApi::class)
private fun Payload(route: String, data: Buffer = Buffer()): io.rsocket.kotlin.payload.Payload =
    buildPayload {
      data(data)
      metadata(RoutingMetadata(route))
    }
